package com.security.spring.service.impl;

import com.security.spring.auth.AuthService;
import com.security.spring.service.AuthorizationService;
import com.security.spring.web.rq.GetTokenMessageDTO;
import com.security.spring.web.rs.TokenMessageDTO;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author Administrator
 */
@Service
public class AuthorizationServiceImpl implements AuthorizationService, ApplicationContextAware, InitializingBean {

    private ApplicationContext applicationContext;
    private List<AuthService> authServices;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void afterPropertiesSet() {
        Map<String, AuthService> serviceBeanMap = applicationContext.getBeansOfType(AuthService.class);
        if (serviceBeanMap.size() > 0) {
            authServices = new ArrayList<>(serviceBeanMap.values());
        }
    }


    @Override
    public TokenMessageDTO doAuth(GetTokenMessageDTO getTokenMessageDTO) {
        AtomicReference<TokenMessageDTO> tokenMessageDTO = new AtomicReference<>(null);
        if (!CollectionUtils.isEmpty(authServices)) {
            authServices.forEach(authService -> {
                System.out.println("===========" + authService);
                try {
                    TokenMessageDTO messageDTO = authService.doAuth(getTokenMessageDTO);
                    if (null != messageDTO) {
                        tokenMessageDTO.set(messageDTO);
                    }
                } catch (Exception e) {
                    System.out.println("异常");
                }
            });
        }
        return tokenMessageDTO.get();
    }
}
